<template>
  <div class="login">
    <van-nav-bar title="登录" />
    <van-form :show-error="false" @submit="login">
      <van-cell-group>
        <van-field
        v-model="mobile"
        type="tel"
        label="手机号"
        placeholder="请输入手机号"
        required
        :rules="rules.mobile"
        />
        <van-field
        v-model="code"
        type="digit"
        label="验证码"
        placeholder="请输入验证码"
        required
        :rules="rules.code"
        />
      </van-cell-group>
      <div class="btn-wrap">
        <van-button type="info">登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { onLogin } from '@/api/user'
export default {
  name: 'login',
  data () {
    return {
      mobile: '15515935005',
      code: '246810',
      rules: {
        mobile: [
          { required: true, message: '手机号不能为空' },
          { pattern: /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/, message: '手机号格式不正确' }
        ],
        code: [
          { required: true, message: '验证码不能为空' },
          { pattern: /^\d{6}$/, message: '验证码为6位' }
        ]
      }
    }
  },
  methods: {
    async login () {
      this.$toast.loading({
        duration: 0, // 持续展示 toast,永远不会关闭
        overlay: true, // 整体添加一个遮罩
        message: '加载中...',
        forbidClick: true // 是否禁止背景点击
      })
      try {
        const res = await onLogin(this.mobile, this.code)
        console.log(res)
        this.$store.commit('user/setTokenInfo', res.data.data)
        this.$toast.success('登录成功')
        this.$router.push('/')
      } catch {
        this.$toast.fail('手机号或验证码错误')
      }
    }
  }
}
</script>

<style lang='scss' scoped>
.login {
  // ::v-deep {
  //   .van-nav-bar {
  //     background-color: #3196fa;
  //       .van-nav-bar__title {
  //         color: #fff;
  //       }
  //   }
  // }
  .btn-wrap {
    padding: 20px;
    .van-button {
      width: 100%;
      color: #fff;
      border-radius: 5px;
    }
  }
}
</style>
